'use client';

import type { IOauthClient, IPagination, IQueryParams } from '@/interfaces';
import {
  OAUTH_CLIENT_REVIEW_STATE_KEY,
  OAUTH_CLIENT_STATE_KEY,
} from '@/lib/constant';
import { queryAllOauthClient, searchOauthClient } from '@/services/api';
import { type ChangeEvent, useContext, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useSearchParams } from 'next/navigation';
import classNames from 'classnames';
import Alert from '@/app/[locale]/alert/alert';
import Image from 'next/image';
import AlertLoad from '@/app/[locale]/alert/load';
import useToast from '@/hooks/useToast';
import { OauthClientAdminContext } from '@/contexts/admin/oauth/client';
import DetailsOauthClientAdminPage from '@/app/[locale]/admin/oauth/client/detail';
import UpdateOauthClientAdminPage from '@/app/[locale]/admin/oauth/client/update';

export default function ListOauthClientAdminPage(this: any) {
  const [currentItemId, setCurrentItemId] = useState<number>();
  const urlSearchParams = useSearchParams();
  const [params, setParams] = useState<IQueryParams>({
    page: urlSearchParams?.has('page')
      ? parseInt(urlSearchParams.get('page') + '')
      : 0,
  });
  const [searchName, setSearchName] = useState('');
  const queryKey = ['/oauth', '/clients', params, searchName];
  const [isCreate, setIsCreate] = useState(false);
  const [detailItem, setDetailItem] = useState<IOauthClient>();
  const [updateItem, setUpdateItem] = useState<IOauthClient>();
  const context = useContext(OauthClientAdminContext);
  const { show } = useToast();

  const queryAllOauthClientQuery = useQuery(
    queryKey,
    async (context) => {
      if (searchName) {
        return (await searchOauthClient({
          query: {
            ...(context.queryKey[2] as any),
            name: context.queryKey[3],
          },
        })) as IPagination<IOauthClient>;
      } else {
        return (await queryAllOauthClient({
          query: context.queryKey[2] as any,
        })) as IPagination<IOauthClient>;
      }
    },
    {
      keepPreviousData: true,
    },
  );

  function onChangeSearch(e: ChangeEvent<HTMLInputElement>) {
    const value = e.target.value;
    setSearchName(value.toLowerCase());
  }

  function onClickCreate() {
    setIsCreate(true);
  }

  function onClickDetail(item: IOauthClient) {
    setDetailItem(item);
    setCurrentItemId(item.id);
  }

  function onClickUpdate(item: IOauthClient) {
    setUpdateItem(item);
  }

  function onClickPrevious() {
    const data = queryAllOauthClientQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.max(0, data.pageable.page - 1);
    setParams({ ...params, page });
  }

  function onClickNext() {
    const data = queryAllOauthClientQuery.data;
    if (!data) {
      show({
        type: 'DANGER',
        message: '数据不存在',
      });
      return;
    }

    const page = Math.min(data.pageable.pages, data.pageable.page + 1);
    setParams({ ...params, page });
  }

  if (queryAllOauthClientQuery.data) {
    const data = queryAllOauthClientQuery.data;

    return (
      <OauthClientAdminContext.Provider
        value={{
          ...context,
          isCreate,
          detailItem,
          updateItem,
          setIsCreate,
          setDetailItem,
          setUpdateItem,
          queryKey,
        }}
      >
        <div className="row">
          <div className="col">
            <div className="vstack gap-4">
              <div className="row">
                <div className="col">
                  <div className="card">
                    <div className="card-header bg-transparent">
                      <div className="row row-cols-auto justify-content-between g-2">
                        <div className="col">
                          <div className="input-group">
                            <span className="input-group-text">
                              <i className="bi bi-search"></i>
                            </span>
                            <input
                              onChange={onChangeSearch}
                              type="search"
                              className="form-control"
                              placeholder="搜索开放认证客户端"
                            />
                          </div>
                        </div>
                        <div className="col">
                          <div className="hstack gap-3"></div>
                        </div>
                      </div>
                    </div>
                    <div className="card-body">
                      <div className="table-responsive">
                        <table className="table table-hover align-middle">
                          <thead>
                            <tr className="text-nowrap">
                              <th scope="col" className="w-10">
                                客户端 ID
                              </th>
                              <th scope="col" className="w-10">
                                名称
                              </th>
                              <th scope="col" className="w-10">
                                站点
                              </th>
                              <th scope="col" className="w-10">
                                回调
                              </th>
                              <th scope="col" className="w-10">
                                状态
                              </th>
                              <th scope="col" className="w-10">
                                审核状态
                              </th>
                              <th scope="col" className="w-10"></th>
                            </tr>
                          </thead>
                          <tbody>
                            {data.content.map((item) => {
                              return (
                                <tr
                                  key={item.id}
                                  className={classNames('text-nowrap', {
                                    'table-active': currentItemId === item.id,
                                  })}
                                >
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.clientId}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.logo ? (
                                      <Image
                                        className="object-fit-cover"
                                        src={item.logo}
                                        alt={item.name}
                                        title={item.name}
                                        width={32}
                                        height={32}
                                      />
                                    ) : (
                                      <span>{item.name}</span>
                                    )}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.website}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.callback}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.state === 'ENABLE' ? (
                                      <i
                                        className="bi bi-patch-check-fill me-2 text-success fs-5"
                                        title="启用"
                                      ></i>
                                    ) : (
                                      <span>
                                        {OAUTH_CLIENT_STATE_KEY[item.state]}
                                      </span>
                                    )}
                                  </td>
                                  <td
                                    className="cursor-pointer"
                                    onClick={onClickDetail.bind(this, item)}
                                  >
                                    {item.reviewState === 'SUCCESSFUL' ? (
                                      <i
                                        className="bi bi-patch-check-fill me-2 text-success fs-5"
                                        title="通过"
                                      ></i>
                                    ) : (
                                      <span>
                                        {
                                          OAUTH_CLIENT_REVIEW_STATE_KEY[
                                            item.reviewState
                                          ]
                                        }
                                      </span>
                                    )}
                                  </td>
                                  <td>
                                    <button
                                      onClick={onClickUpdate.bind(this, item)}
                                      className="btn btn-sm btn-light"
                                      type="button"
                                    >
                                      <i className="bi bi-pencil me-2"></i>
                                      修改
                                    </button>
                                  </td>
                                </tr>
                              );
                            })}
                          </tbody>
                        </table>
                      </div>

                      {data.content.length === 0 && (
                        <Alert message="暂无客户端" />
                      )}

                      <div className="my-4">
                        <nav aria-label="版块分页">
                          <ul className="pagination justify-content-end">
                            <li
                              className={classNames(
                                'page-item',
                                data.pageable.previous ? false : 'disabled',
                              )}
                            >
                              <a
                                onClick={onClickPrevious}
                                className="page-link cursor-pointer"
                              >
                                上一页
                              </a>
                            </li>
                            <li
                              className={classNames(
                                'page-item',
                                data.pageable.next ? false : 'disabled',
                              )}
                            >
                              <a
                                onClick={onClickNext}
                                className="page-link cursor-pointer"
                              >
                                下一页
                              </a>
                            </li>
                          </ul>
                        </nav>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              {detailItem && <DetailsOauthClientAdminPage />}

              {updateItem && <UpdateOauthClientAdminPage />}
            </div>
          </div>
        </div>
      </OauthClientAdminContext.Provider>
    );
  }

  if (queryAllOauthClientQuery.error) {
    return <Alert message={queryAllOauthClientQuery.error} type="error" />;
  }

  return <AlertLoad />;
}
